package com.example.cachedemo.controller;

import com.example.cachedemo.service.CheckService;
import com.example.cachedemo.service.SimpleCache;
import com.example.cachedemo.service.dto.check.ClassCheckRatioDTO;
import org.springframework.cache.CacheManager;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class NewUnit8Controller {
    public final CheckService checkService;
    public final CacheManager cacheManager;

    public NewUnit8Controller(CheckService checkService, CacheManager cacheManager) {
        this.checkService = checkService;
        this.cacheManager = cacheManager;
    }

    @GetMapping("/check/class-ratio/ehcache")
    public ResponseEntity getClassRatioEhcache(String className, String termNo) {
        long time0 = System.currentTimeMillis();
        ClassCheckRatioDTO result = null;
        result = this.checkService.getClassCheckRatio(className, termNo);
        long time1 = System.currentTimeMillis();
        result.setTotalTime(time1 - time0);
        return ResponseEntity.ok(result);
    }

    @DeleteMapping("/check/caches/simple")
    public ResponseEntity deleteCachesSimple(String className, String termNo) {
        String key = className + "-" + termNo;
        SimpleCache.deleteCache(key);
        return ResponseEntity.ok("缓存清除完成");
    }

    @DeleteMapping("/check/caches/ehcache")
    public ResponseEntity deleteCachesEhcache(String className, String termNo) {
        String key = className + "-" + termNo;
        this.cacheManager.getCache("system").evictIfPresent(key);
        return ResponseEntity.ok("缓存清除完成");
    }
}
